package user

import (
	"context"
	"errors"
	"strings"
	"time"

	"mydemo/api/rewark/internal/model"
	"mydemo/api/rewark/internal/svc"
	"mydemo/api/rewark/internal/types"

	"github.com/dgrijalva/jwt-go"
	"github.com/zeromicro/go-zero/core/logx"
)

type JwtLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewJwtLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *JwtLoginLogic {
	return &JwtLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *JwtLoginLogic) JwtLogin(req *types.JwtLoginInput) (resp *types.JwtLoginOutput, err error) {
	if len(strings.TrimSpace(req.Username)) == 0 || len(strings.TrimSpace(req.Password)) == 0 {
		return nil, errors.New("参数错误")
	}
	userDao := &model.User{Name: req.Username}
	if err := userDao.First(l.svcCtx.Db); err != nil {
		return nil, err
	}
	if userDao.Password != req.Password {
		return nil, errors.New("密码不正确")
	}
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	jwtToken, err := l.getJwtToken(l.svcCtx.Config.Auth.AccessSecret, userDao.Name, now, l.svcCtx.Config.Auth.AccessExpire, userDao.Id)
	if err != nil {
		return nil, err
	}
	out := &types.JwtLoginOutput{
		Id:           userDao.Id,
		Name:         userDao.Name,
		Gender:       userDao.Gender,
		AccessToken:  jwtToken,
		AccessExpire: now + accessExpire,
		RefreshAfter: now + accessExpire/2,
	}
	return out, nil
}

func (l *JwtLoginLogic) getJwtToken(secretKey, username string, iat, seconds, userId int64) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = userId
	claims["username"] = username
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}
